using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Sheep_Breeding.Domain.production_b;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Write.Api.DTOs;
using Sheep_Breeding.Write.Api.OperationServices.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sheep_Breeding.Write.Api.OperationServices.Services
{
    /// <summary>
    /// 羊只销售服务实现类
    /// </summary>
    public class SheepSaleService : ISheepSaleService
    {
        private readonly ILogger<SheepSaleService> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<SheepSale> sheepSaleRepository;
        private readonly EFDbContext db;

        public SheepSaleService(
            ILogger<SheepSaleService> logger,
            IMapper mapper,
            IBaseRepository<SheepSale> sheepSaleRepository,
            EFDbContext db)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.sheepSaleRepository = sheepSaleRepository;
            this.db = db;
        }

        /// <summary>
        /// 添加羊只销售信息
        /// </summary>
        /// <param name="dto">添加羊只销售信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddSheepSale(AddSheepSaleDto dto)
        {
            logger.LogInformation("羊只销售信息添加操作");
            var res = new ApiResult();
            try
            {
                if (dto == null)
                {
                    res.msg = "请求数据不能为空";
                    logger.LogWarning("请求数据为空");
                    return res;
                }
                var model = mapper.Map<SheepSale>(dto);
                if (model == null)
                {
                    res.msg = "数据映射失败";
                    logger.LogError("AutoMapper映射失败");
                    return res;
                }
                model.CreateTime = DateTime.Now;
                model.IsDeleted = false;
                var info = await sheepSaleRepository.AddAsyn(model);
                logger.LogInformation($"数据库操作完成，影响行数: {info}");
                if (info > 0)
                {
                    res.success("羊只销售信息添加成功");
                    logger.LogInformation($"羊只销售信息添加成功，ID: {model.Id}");
                }
                else
                {
                    res.msg = "羊只销售信息添加失败";
                    logger.LogWarning("羊只销售信息添加失败");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只销售信息添加异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"添加羊只销售信息失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 删除羊只销售信息（逻辑删除）
        /// </summary>
        /// <param name="dto">删除羊只销售信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> DeleteSheepSale(DeleteSheepSaleDto dto)
        {
            logger.LogInformation("羊只销售信息删除操作");
            var res = new ApiResult();
            try
            {
                var info = sheepSaleRepository.Getlist().FirstOrDefault(x => x.Id == dto.Id && !x.IsDeleted);
                if (info == null)
                {
                    res.msg = "未找到要删除的记录";
                    logger.LogWarning($"未找到ID为{dto.Id}的羊只销售信息");
                    return res;
                }
                info.IsDeleted = true;
                var result = await sheepSaleRepository.Update(info);
                if (result > 0)
                {
                    res.success("删除成功");
                    logger.LogInformation($"逻辑删除羊只销售信息成功，ID: {dto.Id}");
                }
                else
                {
                    res.msg = "删除失败";
                    logger.LogWarning("逻辑删除羊只销售信息失败");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只销售信息删除异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"删除羊只销售信息失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 查询羊只销售信息
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<SheepSaleResultDto>>> SearchSheepSale(SearchSheepSaleDto dto)
        {
            logger.LogInformation("查询羊只销售信息操作");
            var res = new ApiResult<List<SheepSaleResultDto>>();
            try
            {
                var query = sheepSaleRepository.Getlist().Where(x => !x.IsDeleted);
                if (dto.CustomerId.HasValue)
                    query = query.Where(x => x.CustomerId == dto.CustomerId);
                if (dto.SalesmanId.HasValue)
                    query = query.Where(x => x.SalesmanId == dto.SalesmanId);
                if (!string.IsNullOrEmpty(dto.OrderNumber))
                    query = query.Where(x => x.OrderNumber.Contains(dto.OrderNumber));
                if (!string.IsNullOrEmpty(dto.EarNumber))
                    query = query.Where(x => x.EarNumber.Contains(dto.EarNumber));
                if (!string.IsNullOrEmpty(dto.Breed))
                    query = query.Where(x => x.Breed.Contains(dto.Breed));
                if (!string.IsNullOrEmpty(dto.Gender))
                    query = query.Where(x => x.Gender == dto.Gender);
                if (dto.SheepTypeId.HasValue)
                    query = query.Where(x => x.SheepTypeId == dto.SheepTypeId);
                if (!string.IsNullOrEmpty(dto.PenId))
                    query = query.Where(x => x.PenId == dto.PenId);
                if (!string.IsNullOrEmpty(dto.ApprovalUserId))
                    query = query.Where(x => x.ApprovalUserId == dto.ApprovalUserId);
                if (!string.IsNullOrEmpty(dto.FinanceApprovalUserId))
                    query = query.Where(x => x.FinanceApprovalUserId == dto.FinanceApprovalUserId);
                if (!string.IsNullOrEmpty(dto.WarehouseApprovalUserId))
                    query = query.Where(x => x.WarehouseApprovalUserId == dto.WarehouseApprovalUserId);
                if (!string.IsNullOrEmpty(dto.Status))
                    query = query.Where(x => x.Status == dto.Status);
                if (dto.StartSaleDate.HasValue)
                    query = query.Where(x => x.SaleDate >= dto.StartSaleDate);
                if (dto.EndSaleDate.HasValue)
                    query = query.Where(x => x.SaleDate <= dto.EndSaleDate);
                var list = await query.Select(x => mapper.Map<SheepSaleResultDto>(x)).ToListAsync();
                // 关联客户和羊只类型名称
                foreach (var item in list)
                {
                    if (item.CustomerId != null)
                    {
                        var customer = await db.Customers.FindAsync(item.CustomerId);
                        item.CustomerName = customer?.Name;
                    }
                    if (item.SheepTypeId != null)
                    {
                        var sheepType = await db.SheepTypes.FindAsync(item.SheepTypeId);
                        item.SheepTypeName = sheepType?.TypeName;
                    }
                    if (item.SalesmanId != null)
                    {
                        var user = await db.Userinfos.FindAsync(item.SalesmanId);
                        item.SalesmanName = user?.UserName;
                    }
                }
                res.success($"查询到{list.Count}条羊只销售信息", list);
                res.msg = $"查询到{list.Count}条羊只销售信息";
                logger.LogInformation(res.msg);
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"查询羊只销售信息异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"查询羊只销售信息失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 根据ID获取羊只销售详情
        /// </summary>
        /// <param name="id">羊只销售ID</param>
        /// <returns>羊只销售详情</returns>
        public async Task<ApiResult<SheepSaleResultDto>> GetSheepSaleById(long id)
        {
            logger.LogInformation($"获取羊只销售详情，ID: {id}");
            var res = new ApiResult<SheepSaleResultDto>();
            try
            {
                var entity = await sheepSaleRepository.Getlist().FirstOrDefaultAsync(x => x.Id == id && !x.IsDeleted);
                if (entity == null)
                {
                    res.msg = "未找到记录";
                    logger.LogWarning($"未找到ID为{id}的羊只销售信息");
                    return res;
                }
                var dtoResult = mapper.Map<SheepSaleResultDto>(entity);
                res.success("获取详情成功", dtoResult);
                res.msg = "获取详情成功";
                logger.LogInformation($"获取羊只销售详情完成，ID: {id}");
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"获取羊只销售详情异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"获取羊只销售详情失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 更新羊只销售信息
        /// </summary>
        /// <param name="dto">更新羊只销售信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateSheepSale(UpdateSheepSaleDto dto)
        {
            logger.LogInformation("羊只销售信息更新操作");
            var res = new ApiResult();
            try
            {
                var model = mapper.Map<SheepSale>(dto);
                var info = await sheepSaleRepository.Update(model);
                if (info > 0)
                {
                    res.success("羊只销售信息更新成功");
                    logger.LogInformation($"羊只销售信息更新成功，ID: {dto.Id}");
                }
                else
                {
                    res.msg = "羊只销售信息更新失败";
                    logger.LogWarning("羊只销售信息更新失败");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只销售信息更新异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"更新羊只销售信息失败: {ex.Message}";
                return res;
            }
        }
    }
} 